﻿using Microsoft.AspNetCore.Hosting.Server;
using StackExchange.Redis;
using System.Collections.Concurrent;

namespace PropertyManagementSystemAPI.Common.RedisHelper
{
    /// <summary>    
    /// reids数据库操作类    
    /// </summary>    
    public class RedisBase : IDisposable
    {
        //连接字符串    
        private string _connectionString;
        //实例名称    
        private string _instanceName;
        //默认数据库    
        private int _defaultDB;
        private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
        public RedisBase(string connectionString, string instanceName, int defaultDB = 0)
        {
            _connectionString = connectionString;
            _instanceName = instanceName;
            _defaultDB = defaultDB;
            _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
        }
        /// <summary>    
        /// 获取ConnectionMultiplexer    
        /// </summary>    
        /// <returns></returns>    
        private ConnectionMultiplexer GetConnect()
        {
            return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
        }
        /// <summary>    
        /// 获取数据库    
        /// </summary>    
        /// <param name="configName"></param>    
        /// <param name="db">默认为0：优先代码的db配置，其次config中的配置</param>    
        /// <returns></returns>    
        public IDatabase GetDatabase()
        {
            return GetConnect().GetDatabase(_defaultDB);
        }
        public StackExchange.Redis.IServer GetServer(string configName = null, int endPointsIndex = 0)
        {
            var confOption = ConfigurationOptions.Parse(_connectionString);
            return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
        }
        public ISubscriber GetSubscriber(string configName = null)
        {
            return GetConnect().GetSubscriber();
        }
        public void Dispose()
        {
            if (_connections != null && _connections.Count > 0)
            {
                foreach (var item in _connections.Values)
                {
                    item.Close();
                }
            }
        }
    }
}
